<template>
  <div class="home">
    <div class="layout">
      <!-- 左侧分类导航 -->
      <div class="sidebar">
        <el-carousel height="120px" indicator-position="outside" class="sidebar-carousel">
          <el-carousel-item v-for="(item, idx) in carouselItems" :key="idx">
            <div class="carousel-slide">
              <img :src="item.img" class="carousel-img" />
              <div class="carousel-caption">{{ item.caption }}</div>
            </div>
          </el-carousel-item>
        </el-carousel>
        <h2>商品分类</h2>
        <div class="category-list">
          <button 
            :class="{ active: selectedCategory === null }"
            @click="selectedCategory = null"
          >
            全部商品
          </button>
          <button 
            v-for="category in petCategories" 
            :key="category.id"
            :class="{ active: selectedCategory === category.id }"
            @click="selectedCategory = category.id"
          >
            {{ category.name }}
          </button>
        </div>
      </div>

      <!-- 右侧商品列表 -->
      <div class="content">
<div class="content-header">
  <h1 class="main-title">宠物商城</h1>
  <div class="user-actions">
    <el-tooltip content="商城公告" placement="bottom">
      <el-button circle @click="dialogVisible = true" class="notice-icon-btn">
        <el-icon><BellFilled /></el-icon>
      </el-button>
    </el-tooltip>
  </div>
</div>
        <el-dialog v-model="dialogVisible" title="" width="400px" class="notice-dialog">
          <div class="notice-dialog-content">
            <el-icon class="notice-dialog-icon"><BellFilled /></el-icon>
            <h2>商城公告</h2>
            <el-divider></el-divider>
            <div class="notice-text">欢迎光临宠物商城！<br>本周全场宠物八折优惠，快来选购吧！</div>
          </div>
          <template #footer>
            <el-button @click="dialogVisible = false" type="primary">我知道了</el-button>
          </template>
        </el-dialog>
        <div class="pet-list">
          <div v-for="pet in filteredPets" :key="pet.id" class="pet-card">
            <img :src="pet.image" :alt="pet.name" class="pet-img-clickable" @click="showDetail(pet)">
            <div class="pet-info">
              <h3>{{ pet.name }}</h3>
              <p class="description">{{ pet.description }}</p>
              <div class="details">
                <span>年龄：{{ pet.age }}</span>
                <span>性别：{{ pet.gender }}</span>
                <span :class="{ 'vaccinated': pet.vaccinated }">
                  {{ pet.vaccinated ? '已接种疫苗' : '未接种疫苗' }}
                </span>
              </div>
              <p class="price">¥{{ pet.price }}</p>
              <button @click="addToCart(pet)">加入购物车</button>
              <van-button type="primary" size="small" @click="openAction(pet)" class="more-btn">更多</van-button>
            </div>
          </div>
        </div>
        <el-dialog v-model="detailDialogVisible" width="420px" class="pet-detail-dialog" :show-close="true">
          <template #header>
            <div class="pet-detail-header">
              <el-icon style="margin-right:8px;"><BellFilled /></el-icon>
              <span>商品详情</span>
            </div>
          </template>
          <div v-if="detailPet" class="pet-detail-content">
            <img :src="detailPet.image" class="pet-detail-img" />
            <h2>{{ detailPet.name }}</h2>
            <div class="pet-detail-desc">{{ detailPet.description }}</div>
            <el-divider></el-divider>
            <div class="pet-detail-info">
              <div><strong>价格：</strong>¥{{ detailPet.price }}</div>
              <div><strong>年龄：</strong>{{ detailPet.age }}</div>
              <div><strong>性别：</strong>{{ detailPet.gender }}</div>
              <div><strong>疫苗：</strong>{{ detailPet.vaccinated ? '已接种' : '未接种' }}</div>
            </div>
          </div>
        </el-dialog>
        <van-action-sheet v-model:show="actionSheetVisible" :actions="actions" @select="onActionSelect" cancel-text="取消" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { petCategories, pets } from '../data/pets'
import { useRouter } from 'vue-router'

const router = useRouter()
const currentUser = ref('')
import { ElButton, ElDialog, ElTooltip, ElIcon, ElDivider, ElCarousel, ElCarouselItem, ElMessage } from 'element-plus'
import { logout } from '@/services/userService'
import { BellFilled } from '@element-plus/icons-vue'
import { Button as VanButton, ActionSheet as VanActionSheet } from 'vant'

const selectedCategory = ref(null)
const dialogVisible = ref(false)
const actionSheetVisible = ref(false)
const currentPet = ref(null)
const detailDialogVisible = ref(false)
const detailPet = ref(null)

const carouselItems = [
  { img: '/images/11.jpeg', caption: '金毛幼犬 热卖中' },
  { img: '/images/12.jpg', caption: '英短蓝猫 人气爆款' },
  { img: '/images/13.jpg', caption: '萌宠乐园 等你来选' }
]

const actions = [
  { name: '分享' },
  { name: '收藏' }
]

onMounted(() => {
  // 初始化用户信息
  currentUser.value = localStorage.getItem('username') || ''
  
  // 监听登录状态变化
  window.addEventListener('auth-change', (e) => {
    currentUser.value = e.detail.isLoggedIn ? e.detail.username : ''
  })
})

const filteredPets = computed(() => {
  if (!selectedCategory.value) {
    return pets
  }
  return pets.filter(pet => pet.categoryId === selectedCategory.value)
})

const addToCart = (pet) => {
  // 获取当前购物车数据
  const cart = JSON.parse(localStorage.getItem('cart') || '[]')
  
  // 检查商品是否已在购物车中
  const existingItem = cart.find(item => item.id === pet.id)
  
  if (existingItem) {
    // 如果已存在，可以增加数量或提示用户
    ElMessage({
      message: '该商品已在购物车中',
      type: 'warning'
    })
  } else {
    // 添加商品到购物车
    const cartItem = {
      id: pet.id,
      name: pet.name,
      price: pet.price,
      image: pet.image,
      description: pet.description
    }
    cart.push(cartItem)
    localStorage.setItem('cart', JSON.stringify(cart))
    
    ElMessage({
      message: '商品已添加到购物车',
      type: 'success'
    })
  }
}

const openAction = (pet) => {
  currentPet.value = pet
  actionSheetVisible.value = true
}

const onActionSelect = (action) => {
  actionSheetVisible.value = false
  if (action.name === '分享') {
    window.alert('分享功能开发中...')
  } else if (action.name === '收藏') {
    window.alert('收藏功能开发中...')
  }
}

const showDetail = (pet) => {
  detailPet.value = pet
  detailDialogVisible.value = true
}

const handleLogout = async () => {
  try {
    await logout()
    currentUser.value = ''
    localStorage.removeItem('token')
    localStorage.removeItem('username')
    window.dispatchEvent(new CustomEvent('auth-change', {
      detail: { isLoggedIn: false, username: '' }
    }))
    ElMessage.success('已成功登出')
    router.push('/') // 确保跳转到登录页
  } catch (error) {
    ElMessage.error('登出失败')
  }
}
</script>

<style scoped>
.home {
  padding: 0 20px 20px 0px;
}

.layout {
  display: flex;
  gap: 32px;
  align-items: flex-start;
  max-width: 1200px;
  margin: 0 auto;
}

.sidebar {
  /* 顶部导航栏高度66px + 空隙20px */
  top: 86px;
  /* margin-top: 0; 移除多余的margin-top */
  width: 220px;
  background: linear-gradient(135deg, #e0e0e0 0%, #bdbdbd 100%);
  padding: 28px 20px 24px 20px;
  border-radius: 16px;
  box-shadow: 0 4px 16px rgba(120,120,120,0.10);
  height: fit-content;
  position: sticky;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  min-width: 220px;
}

.sidebar h2 {
  margin: 0 0 24px 0;
  color: #333;
  font-size: 1.25em;
  letter-spacing: 1px;
  font-weight: bold;
}

.category-list {
  display: flex;
  flex-direction: column;
  gap: 14px;
  width: 100%;
}

.category-list button {
  text-align: left;
  padding: 12px 18px;
  border: none;
  background: rgba(255,255,255,0.7);
  color: #333;
  border-radius: 8px;
  cursor: pointer;
  font-size: 1.05em;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(180,180,180,0.08);
  transition: background 0.2s, color 0.2s, box-shadow 0.2s;
}

.category-list button:hover {
  background: #bdbdbd;
  color: #fff;
  box-shadow: 0 4px 16px rgba(120,120,120,0.12);
}

.category-list button.active {
  background: linear-gradient(90deg, #757575 0%, #bdbdbd 100%);
  color: #ffe082;
  box-shadow: 0 4px 16px rgba(120,120,120,0.18);
}

.content {
  flex: 1;
}

.content-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 18px;
  gap: 24px;
}

.main-title {
  font-size: 2.1em;
  font-weight: bold;
  color: #333;
  margin: 0;
}

.notice-icon-btn {
  margin-left: 16px;
  background: linear-gradient(90deg, #42b983 0%, #6dd5ed 100%);
  color: #fff;
  border: none;
  box-shadow: 0 2px 8px rgba(66,185,131,0.10);
  transition: background 0.2s, color 0.2s;
}

.notice-icon-btn:hover {
  background: #42b983;
  color: #ffe082;
}

.user-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
}

.user-info span {
  font-size: 0.9em;
}

.notice-dialog :deep(.el-dialog__header) {
  display: none;
}

.notice-dialog-content {
  text-align: center;
  padding: 10px 0 0 0;
}

.notice-dialog-icon {
  font-size: 40px;
  color: #42b983;
  margin-bottom: 8px;
}

.notice-text {
  font-size: 1.1em;
  color: #333;
  margin: 18px 0 0 0;
  line-height: 1.8;
}

.more-btn {
  margin-top: 8px;
  width: 100%;
}

.pet-list {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 24px;
  margin-top: 20px;
}

.pet-card {
  border: 1px solid #eee;
  border-radius: 8px;
  overflow: hidden;
  transition: transform 0.3s;
  background: white;
}

.pet-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}

.pet-card img {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.pet-info {
  padding: 15px;
}

.pet-info h3 {
  margin: 0 0 10px 0;
  color: #333;
}

.description {
  color: #666;
  font-size: 0.9em;
  margin-bottom: 10px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.details {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 10px;
  font-size: 0.9em;
  color: #666;
}

.vaccinated {
  color: #42b983;
}

.price {
  color: #e53935;
  font-weight: bold;
  font-size: 1.2em;
  margin: 10px 0;
}

button {
  width: 100%;
  padding: 10px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #3aa876;
}

.sidebar-carousel {
  width: 100%;
  margin-bottom: 18px;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(120,120,120,0.10);
}
.carousel-slide {
  position: relative;
  width: 100%;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
}
.carousel-img {
  max-width: 100%;
  max-height: 100%;
  border-radius: 8px;
  object-fit: cover;
}
.carousel-caption {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.45);
  color: #fff;
  font-size: 1em;
  padding: 6px 0;
  text-align: center;
  border-radius: 0 0 8px 8px;
}
.pet-img-clickable {
  cursor: pointer;
  transition: box-shadow 0.2s, transform 0.2s;
}
.pet-img-clickable:hover {
  box-shadow: 0 4px 16px rgba(66,185,131,0.18);
  transform: scale(1.04);
}
.pet-detail-dialog :deep(.el-dialog__header) {
  padding-bottom: 0;
}
.pet-detail-header {
  display: flex;
  align-items: center;
  font-size: 1.2em;
  font-weight: bold;
  color: #42b983;
}
.pet-detail-content {
  text-align: center;
}
.pet-detail-img {
  width: 180px;
  height: 180px;
  object-fit: cover;
  border-radius: 12px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(66,185,131,0.10);
}
.pet-detail-desc {
  color: #666;
  margin: 10px 0 16px 0;
  font-size: 1.05em;
}
.pet-detail-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
  font-size: 1.08em;
  color: #333;
  text-align: left;
  margin: 0 auto;
  max-width: 220px;
}
</style>
